var log=require("../utils/log");
var protocol=require("./protocol");

var service_modules={};
function register_service(stype,service){
	if (service_modules[stype]){
		log.warn(service_modules[stype].name+"已经注册了");
	}

	service_modules[stype]=service;
	log.info(service_modules[stype].name+"服务启动");
}

//接收协议
//cmd是二进制:[0001,0002,数据]
//cmd是已经解密后的数据
function on_recv_client_cmd(session,cmd){
	
	//解头
	var head=protocol.decode_head(cmd);
	if (!head)
		return;

	var stype,ctype,utag,proto_type;
	stype=head[0];
	ctype=head[1];
	utag=head[2];
	proto_type=head[3];

	//没找到服务器模块
	if (!service_modules[stype])
		return;

	//假如是转发模块,直接转发,不解码
	if (service_modules[stype].is_transfer){
		service_modules[stype].on_recv_client_cmd(session,stype,ctype,utag,proto_type,cmd);
	}
	else{
		var obj=protocol.decode(proto_type, cmd);
		service_modules[stype].on_recv_client_cmd(session,stype,ctype,utag,proto_type,obj);
	}
}

//接收协议
//cmd是二进制:[0001,0002,数据]
//cmd是已经解密后的数据
function on_recv_app_server_cmd(session,cmd){
	
	//解头
	var head=protocol.decode_head(cmd);
	if (!head)
		return;

	var stype,ctype,utag,proto_type;
	stype=head[0];
	ctype=head[1];
	utag=head[2];
	proto_type=head[3];

	//没找到服务器模块
	if (!service_modules[stype])
		return;

	//假如是转发模块,直接转发,不解码
	if (service_modules[stype].is_transfer){
		service_modules[stype].on_recv_app_server_cmd(session,stype,ctype,utag,proto_type,cmd);
	}
	else{
		var obj=protocol.decode(proto_type, cmd);
		service_modules[stype].on_recv_app_server_cmd(session,stype,ctype,utag,proto_type,obj);
	}
}

//发送协议
function on_send(stype,ctype,utag,proto_type,body){

	var cmd=protocol.encode(proto_type,stype,ctype,utag,body);
	this.send_cmd(cmd);
}

//广播协议
//用在非网关服务器上
function on_broadcast(utag_array,stype,ctype,proto_type,body){

	//服务号,命令号,0,协议类型,(用户数,[用户id数组]),(服务号,命令号,utag,协议类型,body的二进制流)
	//因为是广播,utag为0,utag_array保存了所有的id
	var cmd=protocol.encode(proto_type,stype,ctype,0,body);
	var cmd_len=cmd.length;
	var user_num=utag_array.length;
	var total_len=10+2+user_num*4+2+cmd_len;

	var buf=Buffer.allocUnsafe(total_len);
	buf.writeUInt16BE(10000,0); //广播服务号
	buf.writeUInt16BE(9999,2);  //广播命令号
	buf.writeUInt32BE(0,4);		//utag
	buf.writeUInt16BE(protocol.PROTO_BYTE,8); //二进制发送
	
	var offset=10;
	buf.writeUInt16BE(user_num,offset);
	offset+=2;
	for (var i=0;i<user_num;i++){
		buf.writeUInt32BE(utag_array[i],offset);
		offset+=4;
	}
	buf.writeUInt16BE(cmd_len,offset);
	offset+=2;
	buf.fill(cmd,offset);

	this.send_cmd(buf);
}

function on_disconnect(session){
	for(var key in service_modules){
		service_modules[key].on_disconnect(session,key);
	}
}

var server_manager={
	register_service:register_service,
	on_recv_client_cmd:on_recv_client_cmd,
	on_recv_app_server_cmd:on_recv_app_server_cmd,
	on_send:on_send,
	on_broadcast:on_broadcast,
	on_disconnect:on_disconnect,
	
};

module.exports=server_manager;